<script lang="ts" setup>
// import { isEmpty } from 'lodash'
import { APILogList, APIUserUpInfo } from "@/api/interface"
import Avatar from "@/components/Avatar/index.vue"
import useMarkdown from "@/hooks/useMarkdown/useMarkdown"
import { usePagination } from "@/hooks/usePagination"
import { useUserStore } from "@/store/modules/user"
import cache from "@/utils/cache"
import debounce from "@/utils/debounce"
import dayjs from "dayjs"
import { ElMessage, FormInstance, UploadProps } from "element-plus"
import "md-editor-v3/lib/style.css"
import { storeToRefs } from "pinia"
import { onMounted, reactive, ref, watch } from "vue"

const { getMdiText } = useMarkdown()

const formRef = ref<FormInstance>()

const userStore = useUserStore()

const { user } = storeToRefs(userStore)

const Logloading = ref<boolean>(false)
const Userloading = ref<boolean>(false)
const avatarImgFile = ref<any>(null)
const btnLoading = ref<boolean>(false)
const state: {
  adminInfo: any
  buttonLoading: boolean
  log: {
    event: string
    createtime: string
    info: string
  }[]
  paginationData: {
    total: number
    currentPage: number
    pageSize: number
  }
} = reactive({
  adminInfo: cache.getUser(),
  buttonLoading: false,
  log: [],
  logFilter: {
    limit: 12
  },
  paginationData: {
    total: 0,
    currentPage: 1,
    pageSize: 20
  }
})
console.log(state.adminInfo)

const adminInfo = ref<any>(user) //用于显示

const { paginationData, handleCurrentChange } = usePagination(state.paginationData)

watch(
  () => paginationData.currentPage,
  () => {
    getLog()
  }
)
// 获取日志
const getLog = async () => {
  Logloading.value = true
  const { data, code } = await APILogList({ page: paginationData.currentPage })
  if (code !== 200) return

  paginationData.total = data.count
  state.log = data.list.map((item: any) => {
    item.createtime = dayjs.unix(item.createtime).format("YYYY-MM-DD HH:mm:ss")
    return item
  })
  Logloading.value = false
}

// 初始化
const initLog = async () => {
  await getLog()
  await userStore.getInfo()
}

onMounted(() => {
  initLog()
})

// 上传头像之前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile)

  const image = new Image()
  const reader = new FileReader()

  return new Promise((resolve, reject) => {
    reader.onload = (e) => {
      if (typeof reader.result === "string") {
        image.src = reader.result
        image.onload = () => {
          const width = image.width
          const height = image.height
          if (width !== height) {
            ElMessage.error("头像图片必须为(1:1比例)")
            reject()
          } else {
            resolve()
          }
        }
      } else {
        reject()
      }
    }

    reader.readAsDataURL(rawFile)
  })
}

// 上传头像
const handleRequestUpload = debounce((file: any) => {
  if (file) {
    const allowedFormats = ["image/jpeg", "image/jpg", "image/png"]
    if (!allowedFormats.includes(file.file?.type)) {
      ElMessage({
        type: "error",
        message: "格式错误，只能上传 jpeg / jpg / png 图片格式"
      })
      return
    }

    const URL = window.URL || window.webkitURL
    avatarImgFile.value = file.file
    const imgSrc = URL.createObjectURL(file.file)
    state.adminInfo.avatar = imgSrc
  }
}, 300)

// const onAvatarBeforeUpload = (file: any) => {
//   const allowedFormats = ['image/jpeg', 'image/jpg', 'image/png'];
//   if (!allowedFormats.includes(file.raw?.type)) {
//     ElMessage({
//       type: 'error',
//       message: '格式错误，只能上传 jpeg / jpg / png 图片格式'
//     })
//     return;
//   }

//   const URL = window.URL || window.webkitURL
//   avatarImgFile.value = file.raw
//   const imgSrc = URL.createObjectURL(file.raw)
//   state.adminInfo.avatar = imgSrc
// }

//end
const onSubmit = debounce(async () => {
  try {
    btnLoading.value = true
    const { code } = await APIUserUpInfo({
      nickname: state.adminInfo.nickname,
      gender: state.adminInfo.gender,
      avatar: avatarImgFile.value ?? JSON.stringify({})
    })
    if (code === 200) {
      btnLoading.value = false
      ElMessage({
        type: "success",
        message: `修改成功`
      })
      // getUser()
      await userStore.getInfo()
    }
  } catch (error) {
    console.error(error)
  } finally {
    btnLoading.value = false
  }
}, 300)
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12">
        <el-card class="box-card" v-loading="Userloading">
          <div class="admin-info">
            <!-- @vue-ignore -->
            <el-upload
              class="avatar-uploader"
              action="#"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
              :http-request="handleRequestUpload"
              accept="image/jpg, image/jpeg, image/png ,image/svg"
            >
              <Avatar :avatar="state.adminInfo.avatar" :class-name="'avatar'" :icon-size="110" />
            </el-upload>
            <div class="admin-info-base">
              <div class="admin-nickname">{{ adminInfo.nickname }}</div>
            </div>
            <div class="admin-info-form">
              <!-- :rules="rules" -->
              <el-form @keyup.enter="onSubmit()" label-position="top" ref="formRef" :model="state.adminInfo">
                <el-form-item label="手机号" prop="mobile">
                  <el-input disabled v-model="state.adminInfo.mobile" />
                </el-form-item>
                <el-form-item prop="nickname" label="名称" :rules="[{ required: true, message: '请输入名称' }]">
                  <el-input v-model="state.adminInfo.nickname" />
                </el-form-item>
                <el-form-item
                  prop="gender"
                  label="性别"
                  :rules="[
                    {
                      required: true,
                      message: '请选择性别',
                      trigger: 'change'
                    }
                  ]"
                >
                  <el-select class="w-100" v-model="state.adminInfo.gender" value-key="gender" placeholder="请选择性别">
                    <el-option label="男" :value="1" />
                    <el-option label="女" :value="0" />
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" :loading="btnLoading" @click="onSubmit()"> 保存修改 </el-button>
                  <!-- <el-button @click="onResetForm(formRef)">重置</el-button> -->
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12">
        <el-card v-loading="Logloading" class="box-card" header="日志" shadow="never">
          <el-scrollbar class="scrollbar">
            <el-timeline class="timeline">
              <el-timeline-item v-for="(item, idx) in state.log" :key="idx" size="large" :timestamp="item.createtime">
                {{ item.event }}
                <!-- <MdPreview :modelValue="item.info" /> -->
                <div v-html="getMdiText(item.info)" />
              </el-timeline-item>
            </el-timeline>
            <el-pagination
              class="justify-content-end p10_0"
              :layout="paginationData.layout"
              :page-sizes="paginationData.pageSizes"
              :total="paginationData.total"
              :page-size="paginationData.pageSize"
              :currentPage="paginationData.currentPage"
              @current-change="handleCurrentChange"
            />
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.timeline {
  padding: 0 2px;
}

.admin-info {
  .avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    margin: 60px auto 10px auto;
    border-radius: 50%;
    box-shadow: var(--el-box-shadow-light);
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    overflow: hidden;
    width: 110px;
    height: 110px;
  }

  .avatar-uploader:hover {
    border-color: var(--el-color-primary);
  }

  ::v-deep .avatar_icon_img {
    .avatar {
      display: block;
    }
  }

  .image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .admin-info-base {
    .admin-nickname {
      font-size: 22px;
      color: var(--el-text-color-primary);
      text-align: center;
      padding: 8px 0;
    }

    .admin-other {
      color: var(--el-text-color-regular);
      font-size: 14px;
      text-align: center;
      line-height: 20px;
    }
  }

  .admin-info-form {
    padding: 30px;
  }
}

.el-card {
  box-shadow: none;
  border: none;
  height: calc(100vh - 120px);
}

.scrollbar {
  height: calc(100vh - 120px - 56px - 40px);
}
</style>
